#!/bin/bash

set -e

cd "$(dirname "$0")/.."

function checkout_at() {
  repo=$1; url=$2; sha=$3
  if [ ! -d "$repo" ]; then
    git clone "https://github.com/$url" "$repo"
  fi

  pushd "$repo"
  git fetch && git reset --hard "$sha"
  popd
}

checkout_at "examples/ruby_spec" "ruby/spec" "aaf998fb8c92c4e63ad423a2e7ca6e6921818c6e"

# TODO: Fix these known issues:
#   - [ ] String literals delimited with `=`, e.g. `%=hi=`
#   - [ ] Issue with << operator mistaken for heredocs, e.g. `send(@method){|r,i| r<<i}`
#   - [ ] defined as local var, e.g. `defn.send(@method, defined)`
#   - [ ] Unicode character in symbols, variables, etc, e.g. `:êad`
#   - [ ] Unicode characters in constants, e.g. `CS_CONSTλ = :const_unicode`
#   - [ ] Keyword arguments in lambda `-> a: { }`
#   - [ ] Lambda with call as default argument `-> a=a() { a }`
known_failures="$(cat script/known_failures.txt)"

node_modules/tree-sitter-cli/cli.js parse -q \
  'examples/**/*.rb' \
  $(for file in $known_failures; do echo "!${file}"; done)

example_count=$(find examples -name '*.rb' | wc -l)
failure_count=$(wc -w <<< "$known_failures")
success_count=$(( $example_count - $failure_count ))
success_percent=$(bc -l <<< "100*${success_count}/${example_count}")

printf \
  "Successfully parsed %d of %d example files (%.1f%%)\n" \
  $success_count $example_count $success_percent
